package com.jx.driving.util;

/**
 * 
 * @author wuxiaozeng
 *
 */
public class ByteUtils {

	/**
	 * 直接数值转long
	 */
	public static long byteArraysToLong(byte[] data) {
		long ret = 0;
		for (int i = 0; i < data.length; i++) {
			ret <<= 8;
			ret |= data[i] & 0xFF;
		}
		return ret;
	}

	/**
	 * 字节数组转long
	 */
	public static long byteToLong(byte[] data) {
		long ret = 0;
		for (int i = 0; i < 4; i++) {
			ret <<= 8;
			ret |= data[i] & 0xFF;
		}
		return ret;
	}

	/**
	 * 将byte数组转换成16位的short
	 * 
	 * @param index
	 *            起始位置
	 */
	public static short byteToShort(byte[] b) {
		short s = 0;
		short s0 = (short) (b[0] & 0xff);// 最低位
		short s1 = (short) (b[1] & 0xff);
		s1 <<= 8;
		s = (short) (s0 | s1);
		return s;
	}

	/**
	 * 将16位的short转换成byte数组
	 * 
	 * @param s
	 *            short
	 * @return byte[] 长度为2
	 */
	public static byte[] shortToBytes(short n) {
		byte[] b = new byte[2];
		b[1] = (byte) (n & 0xff);
		b[0] = (byte) ((n >> 8) & 0xff);
		return b;
	}

	public static byte[] intToBytes(int num) {
		byte[] b = new byte[4];
		for (int i = 0; i < 4; i++) {
			b[i] = (byte) (num >>> (24 - i * 8));
		}
		return b;
	}

	public static int bytes2int(byte[] b) {
		// byte[] b=new byte[]{1,2,3,4};
		int mask = 0xff;
		int temp = 0;
		int res = 0;
		for (int i = 0; i < 4; i++) {
			res <<= 8;
			temp = b[i] & mask;
			res |= temp;
		}
		return res;
	}

	/**
	 * Byte转Bit
	 */
	public static String byteToBit(byte b) {
		return "" + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1) + (byte) ((b >> 5) & 0x1)
				+ (byte) ((b >> 4) & 0x1) + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1) + (byte) ((b >> 1) & 0x1)
				+ (byte) ((b >> 0) & 0x1);
	}

}
